package com.ujs.edu.medicine.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.ujs.edu.medicine.dao.*;
import com.ujs.edu.medicine.dataobject.*;
import com.ujs.edu.medicine.util.Result;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.ResultMap;
import org.apache.ibatis.annotations.Select;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author:
 * @Date: Created in 15:16 2020/8/25
 * Description: 聊天控制类
 * Modified By:
 */
@RestController
public class MessageController {

    @Autowired
    YunjiayiMessageMapper yunjiayiMessageMapper;
    @Autowired
    YunjiayiUserMapper yunjiayiUserMapper;
    @Autowired
    YunjiayiStatusMapper yunjiayiStatusMapper;
    @Autowired
    YunjiayiPrescriptionMapper yunjiayiPrescriptionMapper;
    @Autowired
    TableChatMesMapper tableChatMesMapper;

    @Autowired
    private HttpServletRequest request;
    private String gettoken() {
        return request.getHeader("Authorization");
    }




    /*聊天列表*/
    @RequestMapping("/api/chat/list")
    public Result chatList(){
        Result result=new Result();

        String token=gettoken();
        int userId;
        try {
            userId = JWT.decode(token).getClaim("id").asInt();
        } catch (JWTDecodeException j) {
            result.setCode(1);
            result.setMessage("您未登陆，请登陆");
            return result;
        }

        List<TableChatMes> tableChatMes=tableChatMesMapper.selectByFromUserID(userId);

        if (tableChatMes!=null){
            try {
                for (TableChatMes mes:tableChatMes){
                    Author author=yunjiayiUserMapper.selectPartInfo(mes.getTouserid());

                    Integer messageid=yunjiayiMessageMapper.selectMaxDate(mes.getChatid());

                    String content=yunjiayiMessageMapper.selectByChatIdAndLast(messageid);

                    YunjiayiPrescription prescription=yunjiayiPrescriptionMapper.selectByPrimaryKey(mes.getPrescriptionid());

                    Integer unreadMessage=yunjiayiMessageMapper.countunreadmesBystatus(mes.getChatid(),"未读");

                    mes.setAuthor(author);
                    if (prescription!=null){
                        mes.setOpenPrescriptionStatus(Integer.parseInt(prescription.getPrescriptionstatus()));
                    }else {
                        mes.setOpenPrescriptionStatus(1);
                    }

                    mes.setAbstracttest(content);
                    mes.setUnreadNum(unreadMessage);
                }

                result.setCode(0);
                result.setMessage("成功");
                result.setData(tableChatMes);
            }catch (Exception e){
                result.setCode(1);
                result.setMessage("信息出现错误");
                return result;
            }

        }else {
            result.setCode(1);
            result.setMessage("失败");
        }

        return result;
    }


    /*聊天具体信息*/
    @RequestMapping("/api/chat/chatDetail")
    public Result chatDetail(@RequestParam("chat_id")Integer chatId){
        Result result=new Result();
        JSONObject object=new JSONObject();


        String token=gettoken();
        int fromUserId = 0;
        try {
            fromUserId=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您未登陆，请登陆");
            return result;
        }

        TableChatMes tableChatMes=tableChatMesMapper.selectByPrimaryKey(chatId);

        List<YunjiayiMessage> messages=yunjiayiMessageMapper.selectByToAndFromUSer(tableChatMes.getFromuserid(),tableChatMes.getTouserid());



        ChatUser chatUser=new ChatUser();
        chatUser.setId(tableChatMes.getTouserid());
        String touserRealName=yunjiayiUserMapper.selectRealName(tableChatMes.getTouserid());
        chatUser.setRealname(touserRealName);

        object.put("chatUser",chatUser);

        List<Object> list=new ArrayList<>();
        JSONObject object1=null;
        for (YunjiayiMessage message1:messages){
            object1=new JSONObject();
            Author author=yunjiayiUserMapper.selectPartInfo(message1.getFromuserid());
            object1.put("user_id",message1.getFromuserid());
            object1.put("content",message1.getContent());
            object1.put("avatar",author.getAvatar());

            if (message1.getFromuserid()==fromUserId){
                object1.put("isMy",true);
            }else {
                object1.put("isMy",false);
            }

            if (message1.getIsfile().equals(0)){
                object1.put("isFile",false);
            }else {
                object1.put("isFile",true);
            }
            list.add(object1);

            if (message1.getFromuserid()==fromUserId){
                message1.setMessagestatus("已读");
                try {
                    yunjiayiMessageMapper.updateByPrimaryKey(message1);
                }catch (Exception e){
                    result.setCode(1);
                    result.setMessage("修改未读失败");
                    return result;
                }

            }
        }

        object.put("list",list);

        if (tableChatMes!=null){
            result.setCode(0);
            result.setMessage("查询成功");
            result.setData(object);
        }else {
            result.setCode(1);
            result.setMessage("查询失败");
        }

        return  result;
    }



    /*发送聊天消息*/
    @RequestMapping("/api/chat/sendMessage")
    public Result sendMessage(@RequestBody JSONObject object){
        Result result=new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您未登陆，请登陆");
            return result;
        }

        TableChatMes tableChatMes2=tableChatMesMapper.selectByPrimaryKey(object.getInteger("chat_id"));

        YunjiayiMessage message=new YunjiayiMessage();
        if (tableChatMes2!=null) {
            if (object.getBoolean("isFile")) {
                message.setIsfile(1);
            } else {
                message.setIsfile(0);
            }

            message.setFromuserid(myuserid);
            System.out.println(tableChatMes2.getTouserid());
            message.setTouserid(tableChatMes2.getTouserid());
            message.setPrescriptionid(tableChatMes2.getPrescriptionid());
            message.setContent(object.getString("content"));
            message.setMessagestatus("未读");
            message.setChatid(tableChatMes2.getChatid());

            Integer insertMes = yunjiayiMessageMapper.insert(message);
            if (insertMes != 0) {
                result.setCode(0);
                result.setMessage("发送成功");
            } else {
                result.setCode(1);
                result.setMessage("发送失败");
            }
        }else {
            result.setCode(1);
            result.setMessage("出错了");
        }

        return  result;
    }


    /*搜索聊天消息*/
    @RequestMapping("/api/chat/search")
    public Result searchMessage(@RequestParam("content")String content){
        Result result=new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您未登陆，请登陆");
            return result;
        }

        List<TableChatMes> tableChatMes=tableChatMesMapper.selectByFromUserID(myuserid);


        if (tableChatMes!=null){
            for (TableChatMes tableChatMes1:tableChatMes){

                tableChatMes1.setAuthor(yunjiayiUserMapper.selectPartInfo(tableChatMes1.getTouserid()));
                List<YunjiayiMessage> messages=yunjiayiMessageMapper.selectMessageLike(tableChatMes1.getFromuserid(),tableChatMes1.getTouserid(),content);
                if (messages.size()==0){
                    tableChatMes.remove(tableChatMes1);
                }
                tableChatMes1.setRecordNum(messages.size());
                if (tableChatMes.size()==0){
                    break;
                }
            }
            result.setCode(0);
            result.setMessage("查找成功");
            result.setData(tableChatMes);
        }else {
            result.setCode(1);
            result.setMessage("查找失败");
        }

        return result;
    }


    /*移除某项聊天*/
    @RequestMapping(value = "/api/chat",method = RequestMethod.DELETE)
    public Result deleteMessage(@RequestBody Map<String,Integer> map){
        Result result=new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您未登陆，请登陆");
            return result;
        }

        List<TableChatMes> tableChatMes=tableChatMesMapper.selectByFromUserIDOrTouserId(myuserid);

        if (tableChatMes.size()==1){
            int delchat=tableChatMesMapper.deleteByPrimaryKey(map.get("chat_id"));
            int delMess=yunjiayiMessageMapper.deleteByuIdAndToId(myuserid);
            if (delchat!=0&&delMess!=0){
                result.setCode(0);
                result.setMessage("删除成功");
            }else {
                result.setCode(1);
                result.setMessage("删除失败");
            }
        }else {
            int delchat=tableChatMesMapper.deleteByPrimaryKey(map.get("chat_id"));
            if (delchat!=0){
                result.setCode(0);
                result.setMessage("删除成功");
            }else {
                result.setCode(1);
                result.setMessage("删除失败");
            }
        }

        return result;
    }


    /*创建药店聊天*/
    @RequestMapping("/api/chat/new")
    public Result newMessage(@RequestBody JSONObject object){
        Result result=new Result();

        String token=gettoken();
        int myuserid=0;
        try {
            myuserid=JWT.decode(token).getClaim("id").asInt();
        }catch (Exception e){
            result.setCode(1);
            result.setMessage("您未登陆，请登陆");
            return result;
        }

        TableChatMes tableChatMes1=tableChatMesMapper.selectByFromUserIDAndTouserId(myuserid,object.getInteger("shopID"));

        JSONObject object1=new JSONObject();

        if (tableChatMes1!=null){
            object.put("chatID",tableChatMes1.getChatid());
            result.setCode(0);
            result.setMessage("已经有聊天");
            result.setData(tableChatMes1.getChatid());
        }else {
            TableChatMes tableChatMes=new TableChatMes();
            TableChatMes tableChatMes2=new TableChatMes();
            YunjiayiMessage message=new YunjiayiMessage();


            tableChatMes.setFromuserid(myuserid);
            tableChatMes.setTouserid(object.getInteger("shopID"));

            int tabchat=tableChatMesMapper.insert(tableChatMes);

            tableChatMes2.setTouserid(myuserid);
            tableChatMes2.setFromuserid(object.getInteger("shopID"));

            int tachat1=tableChatMesMapper.insert(tableChatMes2);

            message.setChatid(tableChatMes.getChatid());
            message.setIsfile(0);
            message.setMessagestatus("已读");
            message.setTouserid(myuserid);
            message.setFromuserid(object.getInteger("shopID"));
            message.setContent("你好，请问您有什么需要帮助？");

            yunjiayiMessageMapper.insert(message);


            if (tabchat!=0){
                object1.put("chatID",tableChatMes.getChatid());
                result.setCode(0);
                result.setMessage("创建成功");
                result.setData(object1);
            }else {
                result.setCode(1);
                result.setMessage("创建失败");
            }
        }

        return result;
    }
}
